/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package UserProfile;

import IMDBQuery.Cast;
import IMDBQuery.Crew;
import IMDBQuery.IMDBReader;
import IMDBQuery.MovieIMDB;
import com.hp.hpl.jena.ontology.OntModel;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author Xavier Riofrio
 */
public class ClasificacionTranningTest {


    static void ClasificarTranningTest(){
        FileWriter f1 = null;
        try {
            //obtengo las configuraciones del sistema
            Configuration conf = Configuration.getInstance();
            f1 = new FileWriter("C:/RECOMENDADOR/Salidas/COMPARACIONES.txt");
            BufferedWriter b1 = new BufferedWriter(f1);
            //obtengo la lista de peliculas definidas en DBMOVIES (base de peliculas)
            ArrayList<String> movies = UserDataFileReader.readLines(conf.getDBMOVIES());
            //obtengo las calificaciones agrupadas por usuario de la DBRATINGS (base de ratings)
            ArrayList<ArrayList<Calificacion>> agrupados = UserDataFileReader.RatingsReadLines(conf.getDBRATINGS());
            Iterator<ArrayList<Calificacion>> ite = agrupados.iterator();
            //recorro los grupos, osea recorro los usuarios
            while (ite.hasNext()) {
                ArrayList<Calificacion> grupo = ite.next();
                if (!grupo.isEmpty()) {
                    System.out.println("");
                    System.out.println("user " + grupo.get(0).getIdUser());
                    MovieIMDB [] vecMovies = new MovieIMDB [8000];
                    Iterator<Calificacion> ite2 = grupo.iterator();
                    int count=0;
                    //recorro las calificaciones del usuario
                    while (ite2.hasNext()) {
                        Calificacion cal = ite2.next();
                        System.out.print(count+"-");
                        //encuentro la pelicula en la lista
                        String movieLine = findMovieLine(cal.getIdMovie(), movies);
                        //cargo la MovieIMDB
                        MovieIMDB movieIMDb = IMDBReader.getMovieIMDB(movieLine, conf);
                        vecMovies[count]=movieIMDb;
                        count++;
                    }
                    int count2=0;
                    System.out.println("comparando...");
                    LinkedList <String> repetidas = new LinkedList();
                    
                    while(count2<count)
                    {
                        boolean flag1=false;
                        if(vecMovies[count2]!=null)
                        {
                            MovieIMDB movieComp=vecMovies[count2];
                            int count3=count2;
                            int impar=1;
                            while(count3<count)
                            {
                                
                                boolean flag=false;
                                if(vecMovies[count3]!=null)
                                {
                                    MovieIMDB temp=vecMovies[count3];
                                    Cast actores=movieComp.getCast();
                                    boolean rep=repetida(repetidas, temp.getTitle());
                                   if(!temp.getID().equals(movieComp.getID()))
                                   {
                                    for(int i=0;i<actores.getNumActors();i++)
                                    {
                                        boolean existe=Cast.hasActor(actores.getActor(i), temp.getCast());
                                        if(existe==true && rep==false){
                                            System.err.println(movieComp.getTitle()+" iguales A "+temp.getTitle());
                                            repetidas.add(temp.getTitle());
                                            if((impar%2)!=0)
                                                     b1.write(grupo.get(0).getIdUser()+"::"+temp.getID()+"::train");
                                                else
                                                     b1.write(grupo.get(0).getIdUser()+"::"+temp.getID()+"::test");
                                            impar++;
                                            b1.newLine();
                                            b1.flush();
                                            flag=true;
                                           flag1=true;
                                           break;
                                        }
                                    }
                                    if(flag==false)
                                    {
                                        Crew reparto=movieComp.getCrew();
                                        for(int i=0;i<reparto.getNumDirectors();i++)
                                        {
                                            boolean existe=Crew.hasDirector(reparto.getDirector(i), temp.getCrew().getDirectors());
                                            if(existe==true && rep==false){
                                                System.err.println(movieComp.getTitle()+" iguales D "+temp.getTitle());
                                                repetidas.add(temp.getTitle().toString());
                                            if((impar%2)!=0)
                                                     b1.write(grupo.get(0).getIdUser()+"::"+temp.getID()+"::train");
                                                else
                                                     b1.write(grupo.get(0).getIdUser()+"::"+temp.getID()+"::test");
                                            impar++;
                                                
                                                b1.newLine();
                                                b1.flush();
                                            flag=true;
                                           flag1=true;
                                           break;
                                            }
                                        }
                                        if(flag==false)
                                        {
                                            for(int i=0;i<reparto.getNumWriters();i++)
                                            {
                                                boolean existe=Crew.hasWriter(reparto.getWriter(i),temp.getCrew().getWriters());
                                                if(existe==true && rep==false){
                                                    System.err.println(movieComp.getTitle()+" iguales W "+temp.getTitle()); 
                                                    repetidas.add(temp.getTitle());
                                                 if((impar%2)!=0)
                                                     b1.write(grupo.get(0).getIdUser()+"::"+temp.getID()+"::train");
                                                else
                                                     b1.write(grupo.get(0).getIdUser()+"::"+temp.getID()+"::test");
                                                     impar++;
                                                    b1.newLine();
                                                    b1.flush();
                                                      flag=true;
                                                    flag1=true;
                                                     break;
                                                }
                                            }
                                        }
                                    }
                                   }
                                   count3++;
                                }
                                else
                                    count3++;
                            }
                            boolean rep=repetida(repetidas, movieComp.getTitle());
                            if(flag1==true && rep==false)
                            {
                                b1.write(grupo.get(0).getIdUser()+"::"+movieComp.getID()+"::train");
                                repetidas.add(movieComp.getTitle());
                                b1.newLine();
                                b1.flush();
                                
                            }
                            count2++;
                        }
                        else
                            count2++;
                     }
                }
            } 
            b1.close();
        } catch (IOException ex) {
            Logger.getLogger(ClasificacionTranningTest.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                f1.close();
            } catch (IOException ex) {
                Logger.getLogger(ClasificacionTranningTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        archivar();
        
    }
    
    
        private static String findMovieLine(int idMovie, ArrayList<String> movies) {
        Iterator<String> iterator = movies.iterator();
        while (iterator.hasNext()) {
            String pivot = iterator.next();
            String campos[] = pivot.split("::");
            int idMoviePivot = Integer.parseInt(campos[0]);

            if (idMovie == idMoviePivot) {
                return pivot;
            }
        }
        return null;
    }
        
    private static String findMovieId(String idMovie, ArrayList<String> movies) {
        Iterator<String> iterator = movies.iterator();
        while (iterator.hasNext()) {
            String pivot = iterator.next();
            String campos[] = pivot.split("::");
            if (idMovie.equals(campos[1])) {
                return campos[0];
            }
        }
        return null;
    }
        private static boolean repetida(LinkedList<String> repetidas,String idMovie)
        {
          
            
            for(int count=0;count<repetidas.size();count++)
            {
                if(idMovie.equals(repetidas.get(count)))
                    return true;
            }
            
            return false;
        }
       
        
        private static void archivar()
        {
        try {
            FileWriter f1 = null;
            FileWriter f2 = null;
            //obtengo las configuraciones del sistema
            Configuration conf = Configuration.getInstance();
            f1 = new FileWriter("C:/RECOMENDADOR/Salidas/training800.txt");
            f2 = new FileWriter("C:/RECOMENDADOR/Salidas/test800.txt");
            BufferedWriter b1 = new BufferedWriter(f1);
            BufferedWriter b2 = new BufferedWriter(f2);
            //obtengo la lista de peliculas definidas en DBMOVIES (base de peliculas)
            ArrayList<String> movies = UserDataFileReader.readLines(conf.getDBMOVIES());
            ArrayList<String> trainintest = UserDataFileReader.readLines("C:/RECOMENDADOR/Salidas/COMPARACIONES.txt");
            //obtengo las calificaciones agrupadas por usuario de la DBRATINGS (base de ratings)
            ArrayList<String> usuarios = UserDataFileReader.readLines(conf.getDBRATINGS());
           
            //recorro los grupos, osea recorro los usuarios
            int count=0;
            String tiempo="9512315123";
            while (count<trainintest.size()) {
                String campos[]=trainintest.get(count).split("::");
                String user=campos[0];
                String pelicula=findMovieId(campos[1], movies);
                String rating=findUserRating(user,pelicula, usuarios);
                String isTest=campos[2];
                if(!isTest.equals("test"))
                {
                    String linea=user+"::"+pelicula+"::"+rating+"::"+tiempo;
                    System.out.println(linea);
                    b1.write(linea);
                    b1.newLine();
                    b1.flush();
                }
                else
                {
                    String linea=user+"::"+pelicula+"::"+rating+"::"+tiempo;
                    System.out.println(linea);
                    b2.write(linea);
                    b2.newLine();
                    b2.flush();
                }
                count++;
            }
            b1.close();
            b2.close();
                    
        } catch (IOException ex) {
            Logger.getLogger(ClasificacionTranningTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
        private static String findUserRating(String user,String pelicula, ArrayList<String> ratings) {
        Iterator<String> iterator = ratings.iterator();
            while (iterator.hasNext()) {
                    String pivot = iterator.next();
                    String campos[] = pivot.split("::");
                    if(user.equals(campos[0]) && pelicula.equals(campos[1]))
                        return campos[2];
             }
               
            return null;
        }
    
    
}
    
    
    
    

